package cn.market.service.user.impl;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.market.bean.QueryResult;
import cn.market.bean.user.Market;
import cn.market.service.base.DaoSupport;
import cn.market.service.user.MarketService;
import cn.market.utils.Log;
import cn.market.utils.MD5;

@Service@Transactional
public class MarketServiceBean extends DaoSupport<Market> implements
		MarketService {
	private String TAG = "MarketServiceBean";
	@Override
	public boolean isLogin(String username, String password) {
		String sql="select count(m) from Market m where m.password=?2 and m.username=?1";
		Query query = em.createQuery(sql);
		query.setParameter(1, username);
		query.setParameter(2, MD5.MD5Encode(password));
		Long count = (Long)query.getSingleResult();
		if(count>0)
			return true;
		return false;
	}

	public void setVisibleStatu(String [] marketids,boolean statu){
		if(marketids!= null && marketids.length>0){
			StringBuffer jpql=new StringBuffer();
			for(int i=0;i<marketids.length;i++){
				jpql.append('?').append((i+2)).append(',');
			}
			jpql.deleteCharAt(jpql.length()-1);
			Query query = em.createQuery("update Market m set m.loginable=?1 where m.marketid in("+ jpql.toString()+ ")");
			query.setParameter(1, statu);
			for(int i=0;i<marketids.length;i++){
				query.setParameter(i+2, marketids[i]);
			}
			query.executeUpdate();
		}
	}

	@Override
	public boolean isRegisterByUsername(String username) {
		String sql="select count(m) from Market m where m.username=?1";
		Query query = em.createQuery(sql);
		query.setParameter(1, username);
		Long count = (Long)query.getSingleResult();
		if(count>0)
			return true;
		return false;
	}

	@Override
	public void save(Market entity) {
		//String password = MD5.MD5Encode(entity.getPassword());
		//entity.setPassword(password);
		super.save(entity);
	}

	@Override
	public Market findMarketUserById(Integer id) {
		String sql="from Market m where m.id=?1";
		Query query = em.createQuery(sql);
		query.setParameter(1, id);
		Market market = (Market)query.getSingleResult();;
		return market;
	}

	
	
	@Override
	public void delete(Serializable... marketids) {
		this.visiable(false, marketids);
	}

	@Override
	public void enable(Serializable... marketids) {
		visiable(true, marketids);
	}

	private void visiable(boolean isVisiable,Serializable ... marketids ){
		StringBuffer jpql = new StringBuffer("");
		if(marketids != null && marketids.length>0){
			Object [] params = new Object[marketids.length];
			for(int i=0;i<marketids.length;i++){
				jpql.append("?").append(i+2).append(",");
				params[i]=marketids[i];
			}
			if(jpql.lastIndexOf(",") >0 )
				jpql.deleteCharAt(jpql.lastIndexOf(","));
			Query query = em.createQuery("update Market m set m.loginable=?1 where m.id in ("+jpql.toString()+")");
			query.setParameter(1, isVisiable);
			for(int i=0;i<params.length;i++){
				query.setParameter(i+2, params[i]);
			}
			query.executeUpdate();
		}
	}

	@Override
	public QueryResult<Market> getIndexPageMarkets(String hql,
			String wherejpql, int firstindex, int maxresult,
			Object[] queryParams, LinkedHashMap<String, String> orderby) {
		List list = super.getScrollData(hql, wherejpql, firstindex, maxresult, queryParams, orderby);
		QueryResult<Market> qr = new QueryResult<Market>();
		qr.setResultlist(encapsulation2markets(list));
		qr.setTotalrecord(super.getCount());
		return qr;
	}
	
	private List<Market> encapsulation2markets(List list){
		List<Market> markets = new ArrayList<Market>();
		String methodName = "encapsulation2markets()";
		Log.println(TAG, methodName+" -- the list size is:"+list.size());
		if(list != null && list.size()>0){
			for(int i=0;i<list.size();i++){
				Object [] obj = (Object [])list.get(i);
				Market market = new Market();
				market.setId(new Integer(String.valueOf(obj[0])));
				market.setAddress(String.valueOf(obj[1]));
				market.setName(String.valueOf(obj[2]));
				market.setImageName(String.valueOf(obj[3]));
				markets.add(market);
			}
		}
		return markets;
	}

	@Override
	public boolean isexist(Integer marketid) {
		String sql = "select count(1) from market where id=:id";
		SQLQuery query = super.getSession().createSQLQuery(sql);
		query.setParameter("id", marketid);
		List list = query.list();
		if(list != null && list.size()>0){
			Integer count = new Integer (String.valueOf(list.get(0)));
			return count>0;
		}
		return false;
	}
}
